package com.xiaopo.flying.sticker;

import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.Rect;
import ohos.agp.utils.RectFloat;

/**
 * @author wupanjie
 */
public class DrawableSticker extends Sticker {

    private Element drawable;
    private Rect realBounds;

    public DrawableSticker(Element drawable) {
        this.drawable = drawable;
        realBounds = new Rect(0, 0, getWidth(), getHeight());
    }

    @Override
    public Element getDrawable() {
        return drawable;
    }

    @Override
    public DrawableSticker setDrawable(Element drawable) {
        this.drawable = drawable;
        return this;
    }

    @Override
    public void drawPixelMap(Canvas canvas) {
        canvas.save();
        canvas.concat(getMatrix());
        RectFloat rectFloat = new RectFloat();
        rectFloat.left = realBounds.left;
        rectFloat.top = realBounds.top;
        rectFloat.right = realBounds.right;
        rectFloat.bottom = realBounds.bottom;
        canvas.drawPixelMapHolderRect(new PixelMapHolder(((PixelMapElement) drawable).getPixelMap()), rectFloat, new Paint());
        canvas.restore();
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.save();
        canvas.concat(getMatrix());
        drawable.setBounds(realBounds);
        drawable.drawToCanvas(canvas);
        canvas.restore();
    }

    @Override
    public DrawableSticker setAlpha(int alpha) {
        drawable.setAlpha(alpha);
        return this;
    }

    @Override
    public int getWidth() {
        return drawable.getWidth();
    }

    @Override
    public int getHeight() {
        return drawable.getHeight();
    }

    @Override
    public void release() {
        super.release();
        if (drawable != null) {
            drawable = null;
        }
    }
}
